package conceptmaniax.hotelapp.activities;

import java.io.File;
import java.text.ParseException;

import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
import conceptmaniax.hotelapp.adapters.PhotoFragment;
import conceptmaniax.hotelapp.config.Constants;
import conceptmaniax.hotelapp.enums.Language;
import conceptmaniax.hotelapp.managers.RequestManager;
import conceptmaniax.hotelapp.util.GeneralUtils;
import conceptmaniax.hotelapp.util.database.DataHelper;

public class HomepageActivity extends FragmentActivity implements LocationListener {

	private Language language;
	private LocationManager locationManager;
	private String gpsProvider;
	protected Button showInfo;
	protected Button showServices;
	protected Button showGuide;
	protected Button showBooking;
	protected Button requests;
	protected TableLayout callout;
	protected ListView callout_list;
	protected NonSwipeableViewPager homeScreen;
	protected TextView counter;
	private DataHelper dataHelper = new DataHelper(this,
			Constants.DATABASE_NAME);
	static int x=0;
	private final Handler handler = new Handler();

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.homepage);
		RequestManager.getInstance().init(this);

		// location related actions
		this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		final Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		criteria.setSpeedRequired(false);
		criteria.setBearingRequired(false);
		criteria.setAltitudeRequired(false);
		this.gpsProvider = this.locationManager.getBestProvider(criteria, true);
		this.language = GeneralUtils.getLanguage(this);

		if (this.gpsProvider != null) {
			this.locationManager.requestLocationUpdates(this.gpsProvider,
					Constants.MINIMUM_TIME_BETWEEN_UPDATES,
					Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
		}
		showInfo = (Button) findViewById(R.id.hotel_button);
		showServices = (Button) findViewById(R.id.services_button);
		showGuide = (Button) findViewById(R.id.guide_button);
		showBooking = (Button) findViewById(R.id.booking_button);
		homeScreen = (NonSwipeableViewPager) findViewById(R.id.pager);
		requests = (Button) findViewById(R.id.requestsButton);
		callout = (TableLayout) findViewById(R.id.callout_table);
		callout_list = (ListView) findViewById(R.id.callout_listview);
		counter = (TextView) findViewById(R.id.counter);
		
		fillFields(Constants.ABOUT_MENU_NAME);
		homeScreen.getView(callout, showInfo, showServices, showGuide);
	    homeScreen.setAdapter(new PhotoPagerAdapter(getSupportFragmentManager()));
	    homeScreen.setOnPageChangeListener(new OnPageChangeListener() {
	    	
			@Override
			public void onPageSelected(int arg0) {
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
                if(arg0 <= homeScreen.getAdapter().getCount()-1)
                	arg0++;
	    		else
	    			arg0 = 0;
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});	    
	} 

			public class PhotoPagerAdapter extends FragmentPagerAdapter {
			    	int number = getNumberofImages(fillFields(Constants.ABOUT_MENU_NAME));
			        public PhotoPagerAdapter(FragmentManager fm) {
			        super(fm);
			    }

			    @Override
			    public Fragment getItem(int position) {
			    	PhotoFragment fragment = new PhotoFragment();
			        // set arguments here, if required
			        Bundle args = new Bundle();
					args.putString("name",fillFields(Constants.ABOUT_MENU_NAME));
					args.putInt("position", position+1);
					fragment.setArguments(args);
			        return fragment;
			    }
			    
			    @Override
			    public int getCount() {
			    	return number;
			    }
		}
		
		private int getNumberofImages(final String imgName) {
			int i = 0;
	    	for (int y=1; y<=Constants.MAX_IMAGES_PER_ITEM; y++) {
				File scrollImageFile = new File(getFilesDir().getAbsolutePath() + File.separator + Constants.IMAGES_FOLDER + File.separator + Constants.IMAGES_FOLDER + File.separator + imgName + "_" +y + ".jpg");
				if (scrollImageFile.exists()) 
					i++;
	    	}
	    	return i;
		}
		
		private void autoScroll() {
			handler.post(ViewPagerVisibleScroll);
		}
		   
		
		final Runnable ViewPagerVisibleScroll= new Runnable() {
		                @Override
		                public void run() {

		                    if(x <= homeScreen.getAdapter().getCount()-1)
		                    {
		            	    	homeScreen.setCurrentItem(x, true);	
		            	    	handler.postDelayed(ViewPagerVisibleScroll,6000);
		                        x++;
		                    } else if (x > homeScreen.getAdapter().getCount()-1) {
		                    	x = 0;
		            	    	homeScreen.setCurrentItem(x, true);
		            	    	handler.postDelayed(ViewPagerVisibleScroll,6000);
		                        x++;
		                    }
		                }
		            };

		            
	private String fillFields(final String action) {
		String itemQuery = null;
		switch (language) {
		case ENGLISH:
			itemQuery = "SELECT i._id," + "i.name_en," + " i.description_en,"
					+ "i.photo FROM item i," + " menu m, menu_item mi "
					+ "WHERE m._id = mi.menu_id " + "AND i._id = mi.item_id "
					+ "AND m.activity = '" + action + "'";
			break;
		case GREEK:
			itemQuery = "SELECT i._id," + "i.name_gr," + " i.description_gr,"
					+ "i.photo FROM item i," + " menu m, menu_item mi "
					+ "WHERE m._id = mi.menu_id " + "AND i._id = mi.item_id "
					+ "AND m.activity = '" + action + "'";
			break;
		}
		Cursor cursor = dataHelper.getData(itemQuery);
		cursor.moveToNext();
		String temp = cursor.getString(3);
		cursor.close();
    	if ( dataHelper != null ) dataHelper.close();
        return temp;
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (this.dataHelper != null)
			this.dataHelper.close();
		unbindDrawables(findViewById(R.id.homepage_relativelayout));
		System.gc();
	}

	private void unbindDrawables(View view) {

		if (view.getBackground() != null) {
			view.getBackground().setCallback(null);
		}
		if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
				unbindDrawables(((ViewGroup) view).getChildAt(i));
			}
			((ViewGroup) view).removeAllViews();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (this.gpsProvider != null) {
			this.locationManager.requestLocationUpdates(this.gpsProvider,
					Constants.MINIMUM_TIME_BETWEEN_UPDATES,
					Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
		}
		SetButtonActivity.getInstance().setRecognition(false);
		SetButtonActivity.getInstance().setButtons(this, showInfo,
				showServices, showGuide, showBooking, callout, callout_list,
				homeScreen, requests);
		autoScroll();
		
		try {
			int counter = RequestManager.getInstance().getRequestCount();
			this.counter.setText(""+counter);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    // manage message counter
	    if (this.counter.getText().equals("0")) 
	        this.counter.setVisibility(View.INVISIBLE);
	     else
	        this.counter.setVisibility(View.VISIBLE);
	}

	@Override
	public void onLocationChanged(final Location loc) {
	}

	@Override
	public void onProviderDisabled(final String provider) {
	}

	@Override
	public void onProviderEnabled(final String provider) {
	}

	@Override
	public void onStatusChanged(final String provider, final int status,
			final Bundle extras) {
	}

	@Override
	protected void onPause() {
		super.onPause();
		this.locationManager.removeUpdates(this);
	    if (handler!= null) {
	    	x=0;
	        handler.removeCallbacks(ViewPagerVisibleScroll);
	    }
	}

	@SuppressWarnings("unused")
	private boolean lowDPI() {
		final DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		switch (metrics.densityDpi) {
		case DisplayMetrics.DENSITY_HIGH:
			return false;
		case DisplayMetrics.DENSITY_LOW:
			return true; // LDPI
		case DisplayMetrics.DENSITY_MEDIUM:
			return true; // MDPI
		default:
			return false;
		}
	}

	@SuppressWarnings("unused")
	private boolean smallRes() {
		// consider less than 712-height and 400-width as low res.
		final DisplayMetrics display = this.getResources().getDisplayMetrics();
		int width = display.widthPixels;
		int height = display.heightPixels;
		if ((width < 400) && (height < 712)) {
			return true;
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		return super.onCreateOptionsMenu(GeneralUtils.createOptionsMenu(this,
				menu));
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		GeneralUtils.onOptionsItemSelected(this, item);
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected Dialog onCreateDialog(final int id) {
		return GeneralUtils.createAboutUsDialog(this);
	}

}